class PreferencesController < ApplicationController

  before_filter :authorize, :only => [:index, :get_request_form, :delete_photo]

  def index
    @user = get_session_user
    @user.password = ""
    clear_flash_info
  end

  def update_profile
    return if check_params(params[:user].nil?)

    profile_data = params[:user]

    @user = User.find(get_session_user.id)

    p = profile_data[:password] = profile_data[:password].strip
    pc = profile_data[:password_confirmation] = profile_data[:password_confirmation].strip
    if p || !p.blank?
      profile_data[:password_confirmation] = User.encrypt(pc)
      profile_data[:password] = User.encrypt(p)
    end
    
    if @user.update_attributes(profile_data)
      set_flash_info(FlashInfo.new("Your profile has been updated.", FlashInfo::NOTICE))
      set_session_user(@user)
    else
      clear_flash_info
    end

    @user.password = ""
    @user.password_confirmation = ""
    render :action => :index
  end

  def get_request_form
    @user = get_session_user
    render :partial => "request_form"
  end      
    
  def delete_photo
    get_session_user.update_attribute(:photo, nil)
    # reload user in session
    set_session_user(get_session_user)
    @user = get_session_user
    render :partial => "user_photo"
  end
  
  def request_new_status
    request = params[:request]
    return if check_params(params[:request].nil?)
    if request[:status] == "author"
      request_author(request[:comment])
    elsif request[:status] == "teacher"
      request_teacher(request[:comment])
    else
      render :text => "No type selected" and return
    end
  end
  
  private

  def request_author(comment_)
    RequestAuthor.deliver_request(get_session_user,comment_)
    render :text => "Request for author status has been sent." and return
  end
  
  def request_teacher(comment_)
    RequestTeacher.deliver_request(get_session_user,comment_)
    render :text => "Request for teacher status has been sent." and return
  end
end
